package com.jf.cloud.service.sysmanager.handler;

import com.google.gson.Gson;
import com.jf.cloud.service.sysmanager.entity.SysStaff;
import com.jf.cloud.service.sysmanager.handler.WxSmalleDecode.WXCore;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jf.cloud.component.redis.global.services.GlobalRedisService;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.SysConstant;
import com.jf.cloud.service.sysmanager.entity.SmallCodeOpenId;
import com.jf.cloud.service.sysmanager.support.connect.HttpClientHandle;
import com.jf.cloud.service.sysmanager.support.connect.MySecureProtocolSocketFactory;
import com.jf.cloud.service.sysmanager.support.entity.Result;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Date: 2017/12/5
 * Time: 18:04
 * Description:token 处理器
 */
@Component
public class TokenHandler {

    Logger log = LoggerFactory.getLogger(TokenHandler.class);

    private Gson gson = new Gson();

    @Autowired
    private GlobalRedisService redisService;

    /**
     * 存放后台 token
     *
     * @param token
     * @param uid
     */
    public void putSysToken(String token, String uid, String content) {
        String oldToken = redisService.getString(SysConstant.UID_SYSTEM_TOKEN_PREFIX + uid);
        if (oldToken != null && !oldToken.equals("")) {
            redisService.removeString(SysConstant.TOKEN_SYSTEM_PREFIX + oldToken);
        }
        redisService.putString(SysConstant.UID_SYSTEM_TOKEN_PREFIX + uid, token);
        redisService.putString(SysConstant.TOKEN_SYSTEM_PREFIX + token, content);
    }

    /**
     * 通过用户token获取用户ID
     *
     * @param token
     * @return
     */
    public String getSysStaffByToken(String token) {
        return redisService.getString(SysConstant.TOKEN_SYSTEM_PREFIX + token);
    }

    /**
     * 通过用户token获取用户ID
     *
     * @param token
     * @return
     */
    public SysStaff getSysStaffInfoByToken(String token) {
        try {
            String content = redisService.getString(SysConstant.TOKEN_SYSTEM_PREFIX + token);
            if (StringUtil.isEmail(content)){
                return null;
            }
            SysStaff sysStaff = gson.fromJson(content,SysStaff.class);
            return sysStaff;
        }catch (Exception e){
            log.error("error",e);
            return null;
        }

    }

    /**
     * 移除后台token、uid
     * 
     * @author 朱建文 创建时间：2017年12月20日 下午1:55:12
     */
    public void removeSysToken(String token, String uid){
    	redisService.removeString(SysConstant.UID_SYSTEM_TOKEN_PREFIX + uid);
    	redisService.removeString(SysConstant.TOKEN_SYSTEM_PREFIX + token);
    }

    /**
     * 存放前台用户 token
     *
     * @param token
     * @param uid
     */
    public void putToken(String token, String userinfo,String uid) {
        String oldToken = redisService.getString(SysConstant.UID_2_TOKEN_PREFIX + uid);
        if (oldToken != null && !oldToken.equals("")) {
            redisService.removeString(SysConstant.TOKEN_PREFIX + oldToken);
        }
        redisService.putString(SysConstant.UID_2_TOKEN_PREFIX + uid, token);
        redisService.putString(SysConstant.TOKEN_PREFIX + token, userinfo);
    }

    /**
     * 通过用户token获取用户ID(不区分前后台)
     *
     * @param token
     * @return
     */
    public String getCommUserInfoByToken(String token) {
        String uid = redisService.getString(SysConstant.TOKEN_SYSTEM_PREFIX + token);
        if (StringUtil.isNotEmpty(uid)){
            if (uid.equals("null")){
                uid = redisService.getString(SysConstant.TOKEN_PREFIX + token);
                if (StringUtil.isNotEmpty(uid)){
                    if (uid.equals("null")){
                        return null;
                    }
                }
            }
        } else {
            uid = redisService.getString(SysConstant.TOKEN_PREFIX + token);
            if (StringUtil.isNotEmpty(uid)){
                if (uid.equals("null")){
                    return null;
                }
            }
        }
        return uid;
    }

    /**
     * 移除后台token、uid
     * 
     * @author 朱建文 创建时间：2017年12月20日 下午1:55:12
     */
    public void removeToken(String token, String uid){
    	redisService.removeString(SysConstant.UID_2_TOKEN_PREFIX + uid);
    	redisService.removeString(SysConstant.TOKEN_PREFIX + token);
    }
    
    /**
     * 获取微信小程序的openId
     * 
     * @author 朱建文 创建时间：2018年5月9日 下午1:54:29
     */
    public Result<SmallCodeOpenId> getWxSmallCodeOpenId(String appid,  String secret,  String jsCode) {
		Result<SmallCodeOpenId> result = new Result<SmallCodeOpenId>();
		result.setCode(-1);
		result.setMessage("获取微信小程序openId失败！");
        try {
        	
        	String url = "https://api.weixin.qq.com/sns/jscode2session";
        	HttpClient httpClient = new HttpClient();
        	PostMethod postMethod = new HttpClientHandle().getPostMethod(url, "UTF-8");
        	postMethod.addParameter("appid", appid);
        	postMethod.addParameter("secret", secret);
        	postMethod.addParameter("js_code", jsCode);
        	postMethod.addParameter("grant_type", "authorization_code");
        	
    		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();  
    		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
    		
    		int stateCode = httpClient.executeMethod(postMethod);
            String resultStr = postMethod.getResponseBodyAsString();
            if (stateCode != 200) {
            	log.info("获取微信小程序openId失败！ " + appid + " " + secret + " " + jsCode);
            	result.setMessage("获取微信小程序openId失败！");
            	return result;
			}
            
            SmallCodeOpenId smallCodeOpenId = JsonUtil.toPOJO(resultStr, SmallCodeOpenId.class);
            if(StringUtil.isNotEmpty(smallCodeOpenId.getOpenid())){
            	result.setCode(0);
            	result.setData(smallCodeOpenId);
            	result.setMessage("获取微信小程序openId成功！");
                return result;
            }
        } catch (Exception e) {
            log.error("获取微信小程序openId出错！", e);
        }
        return result;
    }

    /**
     * 小程序解密数据获取手机号
     *
     * @author wr 创建时间：2018年5月14日 下午17:25
     */
    public Result<String> getWxSmalldDcryptPhone(String appid, String sessionKey, String encryptedData , String iv) {
        Result<String> result = new Result<String>();
        result.setCode(-1);
        result.setMessage("获取微信小程序手机号失败！");
        try {
            String resultStr = WXCore.decrypt(appid, encryptedData, sessionKey, iv);
            if(StringUtil.isNotEmpty(resultStr)){
                result.setCode(0);
                result.setData(resultStr);
                result.setMessage("获取微信小程序手机号成功！");
                return result;
            }
        } catch (Exception e) {
            log.error("获取微信小程序手机号出错！", e);
        }
        return result;
    }
}

